package com.xxwy.ddu.cms.manager.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.xxwy.ddu.cms.authonrize.entity.BaseUser;
import com.xxwy.ddu.cms.authonrize.entity.Role;
import com.xxwy.ddu.cms.authonrize.service.IMenuMainService;
import com.xxwy.ddu.cms.authonrize.service.IUserService;
import com.xxwy.ddu.common.exception.IllegalParameterException;
import com.xxwy.ddu.common.util.RUtil;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xxwy
 * on 2018/9/10 0010
 */
@RequestMapping("userInfo")
@RestController
@Log
public class UserManagerController {

    @Autowired
    IUserService iUserService;

    @Autowired
    IMenuMainService iMenuMainService;

    @GetMapping("/all")
    public ResponseEntity getAllUser(
            @RequestParam int page,
            @RequestParam int limit) {
        Page<BaseUser> baseUserPage = iUserService.selectUserWithRole(new Page<>(page, limit));
        return RUtil.success(baseUserPage);
    }

    @DeleteMapping("/all")
    public ResponseEntity delectAllUser(@RequestBody List<BaseUser> users) {
        List<Integer> uids = null;
        if (users != null) {
            uids = users.stream().map(x -> x.getuId()).collect(Collectors.toList());
        }
        iUserService.deleteBatchIds(uids);
        return RUtil.success();
    }

    @PutMapping("lock")
    public ResponseEntity updateUserlock(@RequestParam int id, @RequestParam boolean block) {
        BaseUser build = BaseUser.builder().isBlock(block).uId(id).build();
        iUserService.updateById(build);
        return RUtil.success();
    }

    @DeleteMapping("user/{id}")
    public ResponseEntity deleteUser(@PathVariable int id) {
        iUserService.deleteById(id);
        return RUtil.success();
    }

    @PostMapping("user")
    public ResponseEntity insertUser(@RequestBody @Valid BaseUser baseUser) {
        log.info(baseUser.toString());
        //判断baseUser选择了角色：
        if(baseUser.getRoles()!=null&& !baseUser.getRoles().isEmpty()) {
            iUserService.insertUserWithRole(baseUser);
            return RUtil.success();
        }else {
            throw new IllegalParameterException("请求参数应添加角色信息");
        }
    }

}
